* This program takes input from a stream.
* Encodes or Decodes a Caesar Cipher given
* an offset.
* A typical command line would be:
* "cc_code d 7 < cipher.dat"
* "cc_code d 7 < cipher.dat > results.txt"
* "cc_code e 6 < results.txt > cipher.dat"
* "d" decodes, "e" encodes.
*/
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
/*---------------------*/
#define A 65
#define Z 90
/*----------------------*/
char alpha[26];
char buffer[16000];
/*-----------------------*/
void fill_array(char *array,int offset);
/* Prototypes */
void print_array(char *array);
int lookup_letter(int letter,char *array);
int test_letter(int letter);
/*-----------------------*/
int main(int argc, char *argv[])
{
int offset,i;
char ch;
if((argc != 3))
{
printf("Use: %s d offset < input_file (To Decode)\n", argv[0]);
printf(" %s e offset < input_file (To
Encode)\n", argv[0]);
return 1;
}
if (strcmp(argv[1],"d")==0)
offset=(26 - atoi(argv[2]));
else offset=atoi(argv[2]);
fill_array(alpha,offset);
for( i = 0;((ch = getchar())
!= EOF); i++ )
buffer[i] = (char)test_letter(ch);
buffer[i] = '\0';
printf( "%s\n", buffer
);
return 0;
}
/*-------------------*/
void fill_array(char *array,int offset)
{
int i,j,k=0;
for(i=(A + offset);i
<=(Z + offset); i++)
{
j=i;
if (j>Z)
{
j=(j-26); /* If we went past Z, go back around. */
}
array[k]=j;
k++;
}
}
/*------------------*/
/* Kept this procedure for troubleshooting */
void print_array(char *array)
{
int i;
for(i=0;i <= 25;i++)
{
printf("%c",array[i]);
}
printf("\n");
}
/*------------------*/
int lookup_letter(int letter,char *array)
{
int i=0;
while (array[i] != letter)
{
i++;
}
return (i + A);
}
/*------------------*/
int test_letter(int letter)
{
int ch;
ch=toupper(letter);
if isalpha(ch)
return lookup_letter(ch,alpha);
else
return ch;
}
/*------------------*/